import Vue from 'vue'
import Vuex from 'vuex';

Vue.use( Vuex )

var state = {
  count: 0,
  // 通过本地存储，解决页面刷新后，store被重置的问题（状态丢失）。
  isLogin: sessionStorage.getItem( 'isLogin' ) ? sessionStorage.getItem( 'isLogin' ) : '0',
  token: sessionStorage.getItem( 'token' ) ? sessionStorage.getItem( 'token' ) : '',
  userInfo: sessionStorage.getItem( 'userInfo' ) ? JSON.parse( sessionStorage.getItem( 'userInfo' ) ) : {}
}
// 计算属性的功能
var getters = {
  getStateCount ( state ) {
    return state.count;
  },
  getToken ( state ) {
    return state.token;
  }
}

var actions = {
  // 这里函数名称，要和dipatch()的任务名一个名称
  //  payload,是用来接收dispatch()传递的参数
  loginAc ( { commit, state, getters }, payload ) {
    console.log( payload )

    commit( "loginMt", payload )  // 触发mutatinos中的事件，
  },
  countAc ( context, payload ) {
    console.log( payload )
    payload = payload?.number || payload;
    context.commit( 'countMt', payload )
  }
}
var mutations = {
  countMt ( state, payload = 1 ) {
    state.count += payload
  },
  loginMt ( state, payload ) {
    state.isLogin = payload.isLogin;
    state.token = payload.token;
    state.userInfo = payload.userInfo;
  }
}

// vuex 3.x 中得语法：
const store = new Vuex.Store( {
  state,
  getters,
  actions,
  mutations
} )

// 使用es6 export default 公开store;
export default store;